<template>
  <div class="main">
    <el-table
      :data="menuData.data"
      style="width: 100%; margin-bottom: 40px"
      default-expand-all
      row-key="id"
    >
      <el-table-column prop="menuName" label="菜单列表" width="150" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <!-- {{ scope.row.id }} -->
          <el-checkbox-group v-model="selectAll">
            <el-checkbox
              :label="scope.row.id"
              @change="checkAll($event, scope.row.id)"
              v-if="scope.row.children === undefined"
            >
              全选
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column label="功能权限">
        <template #default="scope">
          <el-checkbox-group
            v-model="powerGrouping[scope.row.id]"
            @change="checkedChange($event, scope.row.id)"
          >
            <el-checkbox
              v-for="(item, index) in scope.row.power"
              :key="item.id"
              :label="item.id"
              size="large"
              border
            >
              <!-- {{ item.menuName + item.id }} -->
              {{ item.menuName }}
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-button type="primary" color="#ea5b24" @click="editPower()"
    >保存</el-button
  >
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { findMenuListApi, editRoleApi, findMenuApi } from "../../../api/index";
import { usePermissStore } from "../../../store/permiss";
import { isEqual } from "lodash";

const pinia = usePermissStore();
//所有菜单数据
let powerData: any = reactive([]);
let menuData: any = reactive([]);

//角色权限模型
const roleModel: any = reactive({
  id: null,
  menus: [],
});

//当前角色id
const props = defineProps(["adminId"]);
//当前角色权限列表数据
let rolePowerData: any = reactive([]);
//当前角色权限id数组对象
let powerGrouping = reactive({});
// 所有权限id数组对象
let allPower = reactive({});
// 全选操作数据
const selectAll = ref([]);
// 查询菜单列表
const findMenuList = async () => {
  //获取所有菜单列表
  await findMenuListApi().then((res) => {
    powerData.data = JSON.parse(JSON.stringify(res.data.data));
    menuData.data = filterateData(res.data.data, 1);
  });
  await createGrouping(menuData.data, powerGrouping);
  await getPowerByMenuId(menuData.data, powerData.data);
  //获取当前角色权限
  await findMenuApi(props.adminId).then((res) => {
    rolePowerData = res.data.data;
  });
  if (rolePowerData) {
    await getAllNodeId(rolePowerData, powerGrouping);
  }
  if (powerData.data) {
    await createGrouping(menuData.data, allPower);
    await getAllNodeId(powerData.data, allPower);
  }
  Object.keys(powerGrouping).forEach((val) => {
    if (powerGrouping[val].length > 0) {
      if (
        isEqual(powerGrouping[val], allPower[val]) &&
        !selectAll.value.includes(parseInt(val))
      ) {
        selectAll.value.push(parseInt(val));
      }
    }
  });
};

//过滤菜单递归方法
const filterateData = (data: any, type: number) => {
  if (!data) return;
  let menu = data;
  menu.forEach((val, index, arr) => {
    if (val.type != type) {
      delete arr[index];
    }
    if (val.children.length > 0) {
      filterateData(val.children, type);
    }
    if (val.children[0] == undefined) {
      delete val.children;
    }
  });
  return menu;
};
// 根据菜单id添加功能
const getPowerByMenuId = (menu: any, data: any) => {
  menu.forEach((val, index, all) => {
    if (val.id === data[index].id && val.children == undefined) {
      all[index].power = data[index].children;
    } else {
      getPowerByMenuId(val.children, data[index].children);
    }
  });
};

//递归取出所有权限id
const getAllNodeId = (data: any, group) => {
  data.forEach((val, index, all) => {
    if (val.children.length > 0) {
      val.children.forEach((el) => {
        if (el.type === 2) {
          group[val.id].push(el.id);
        }
      });
      if (val.children[0].type === 1) {
        getAllNodeId(val.children, group);
      }
    }
  });
};

// 递归生成分组对象
const createGrouping = (data, group) => {
  data.forEach((val, index, arr) => {
    group[val.id] = [];
    if (val.children != undefined) {
      createGrouping(val.children, group);
    }
  });
};

//连带勾选
const checkedChange = (value, id) => {
  if (value.length > 0) {
    powerGrouping[id].includes(allPower[id][0])
      ? true
      : powerGrouping[id].push(allPower[id][0]);
    if (
      isEqual(
        powerGrouping[id].sort((a, b) => a - b),
        allPower[id].sort((a, b) => a - b)
      )
    ) {
      selectAll.value.push(id);
    } else {
      if (selectAll.value.includes(id)) {
        selectAll.value.splice(selectAll.value.indexOf(id), 1);
      }
    }
  } else {
    if (selectAll.value.includes(id)) {
      selectAll.value.splice(selectAll.value.indexOf(id), 1);
    }
  }
};

// 全选
const checkAll = (val, id) => {
  if (val) {
    powerGrouping[id] = allPower[id];
  } else {
    powerGrouping[id] = [];
  }
};

// 修改角色权限
const editPower = () => {
  let rolePowerId = [];
  Object.keys(powerGrouping).forEach((item) => {
    rolePowerId.push(...powerGrouping[item]);
  });
  //保存
  roleModel.id = props.adminId;
  roleModel.menus = rolePowerId;
  editRoleApi(roleModel).then((res) => {
    if (res.data.code === 2000) {
      pinia.setDisabled();
      ElMessage({
        message: "保存成功.",
        type: "success",
      });
    } else {
      ElMessage.error("保存失败");
    }
  });
};

onMounted(() => {
  findMenuList();
});
</script>
